//
//  AllSearchVC.m
//  ImGuider
//
//  Created by 王鹏宇 on 2018/1/8.
//  Copyright © 2018年 imguider. All rights reserved.
//

#import "AllSearchVC.h"
#import "SearchResultsControllerTableViewController.h"
#import "RecommndCityListCell.h"
#import "PlayerItem.h"
#import "SearchHeaderView.h"
#import "SearchResultCell.h"
#import "CityVC.h"
#import "ScenicDescribeVC.h"
@interface AllSearchVC ()<UISearchResultsUpdating,UISearchBarDelegate,UISearchControllerDelegate,UITableViewDataSource,UITableViewDelegate,RecommndCityListCellDelegate,SearchResultsControllerTableViewControllerDelegate,SearchHeaderViewDelegate, SearchResultCellDelegate>


@property (nonatomic, strong) UISearchController * searchController;
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSMutableArray * dataSource;

@property (nonatomic, strong) NSMutableArray * countyListArray;
@property (nonatomic, strong) SearchResultsControllerTableViewController *searchResultTVC;

@end

@implementation AllSearchVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setUpSearchController];
    [self setUp];
    [self loadDataSource];
    
}

- (UIBarButtonItem *)rt_customBackItemWithTarget:(id)target action:(SEL)action {
    
    return nil;
}

- (void)setUp {
    
    self.isHiddenPlayStatusButton = YES;
    [self setNavThemeGradient];
    
    CGFloat H =  kScreenHeight;
    CGFloat space = kNavigationBarHeight;
    self.tableView= [[UITableView alloc]initWithFrame:CGRectMake(0, kNavigationBarHeight,kScreenWidth, H - space ) style:UITableViewStylePlain];
    
    // ios 11  scrollvew 的位置调整
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior =UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
    //    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    //    //    [self.tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"HeaderView"];
    //
    [self.tableView registerClass:[RecommndCityListCell class] forCellReuseIdentifier:@"RecommndCityListCell"];
    
    [self.tableView registerClass:[SearchHeaderView class] forHeaderFooterViewReuseIdentifier:@"SearchHeaderView"];
    [self.tableView registerClass:[SearchResultCell class] forCellReuseIdentifier:@"SearchResultCell"];
    self.view.backgroundColor = kBGColor;
    self.tableView.backgroundColor = kBGColor;
    //    if (![AppManager sharedManager].cityver || ![[AppManager sharedManager].version.cityver isEqualToString:[AppManager sharedManager].cityver]) {
    //
    //        [NetAPIManager getCityListWithVersion:[AppManager sharedManager].version.cityver block:^(NSString *result, NSError *error) {
    //
    //            if (!error) {
    //
    //               /// [self loadDataSource];
    //            }
    //        }];
    //        return;
    //    }
    //
    //    [self loadDataSource];
}

- (void)  setUpSearchController {
    
    //创建 搜索使用的表示图控制器
    _searchResultTVC = [[SearchResultsControllerTableViewController alloc] initWithStyle:UITableViewStylePlain];
    _searchResultTVC.delegate = self;
    //tvc.view.backgroundColor = [UIColor blueColor];
    
    //创建搜索控制器
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:_searchResultTVC];
    _searchController.searchResultsUpdater = self;
    _searchController.delegate = self;
    _searchController.searchBar.delegate = self;
    _searchController.dimsBackgroundDuringPresentation = NO;
    _searchController.hidesNavigationBarDuringPresentation = NO;
    _searchController.searchBar.frame = CGRectMake(0,0, kScreenWidth,44);
    _searchController.searchBar.showsCancelButton = YES;
    
    for(id cc in [_searchController.searchBar.subviews[0] subviews]) {
        
        if([cc isKindOfClass:[UIButton class]]) {
            
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    }
    
    
    _searchController.searchBar.placeholder = MYLocalizedString(@"CHANGECITY_SEARCH", nil);
    
    _searchController.searchBar.searchBarStyle = UISearchBarStyleDefault;
    
    _searchController.searchBar.barTintColor = [UIColor whiteColor];
    _searchController.searchBar.tintColor = [UIColor whiteColor];
    
    [_searchController.searchBar sizeToFit];
    
    CGFloat height;
    if (@available(iOS 11.0, *)) {
        
        height = 32.0f;
        [_searchController.searchBar setSearchFieldBackgroundPositionAdjustment: UIOffsetMake(0, -3)];
    }else{
        height = 32.0f;
    }
    UIImage* searchBarBg = [IGUtil getImageWithColor:[UIColor colorWithWhite:1 alpha:0.3] andHeight:height];
    
    [_searchController.searchBar setBackgroundImage:searchBarBg];
    [_searchController.searchBar setBackgroundColor:[UIColor clearColor]];
    [_searchController.searchBar setSearchFieldBackgroundImage:searchBarBg forState:UIControlStateNormal];
    
    [_searchController.searchBar setImage:[UIImage imageNamed:@"clear_placeholder"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
    [_searchController.searchBar setImage:[UIImage imageNamed:@"clear_placeholder"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateHighlighted];
    
    UITextField *searchField = [_searchController.searchBar valueForKey:@"searchField"];
    
    
    searchField.tintColor = [UIColor whiteColor];
    searchField.textColor = [UIColor whiteColor];
    searchField.font = Font(14);
    [searchField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    
    if (searchField) {
        searchField.layer.cornerRadius = 3.0f;
        searchField.layer.masksToBounds = YES;
    }
    
    UIImage *image = [UIImage imageNamed:@"searchIcon"];
    UIImageView *iconView = [[UIImageView alloc] initWithImage:image];
    iconView.frame = CGRectMake(0, 0, 16 , 16);
    searchField.leftView = iconView;
    //_searchController.searchBar.translatesAutoresizingMaskIntoConstraints = false;
    
    self.navigationItem.titleView = _searchController.searchBar;
    
    
}


- (void)loadDataSource {
    
    //    City * city = [[City alloc] init];
    //    city.cid = @(11);
    //    self.currentCity = city;
    
    self.dataSource = [NSMutableArray arrayWithArray:[AppManager sharedManager].searchResultArray];
    
    self.countyListArray = [NSMutableArray arrayWithArray:[AppManager sharedManager].recommendArray];
    [self.tableView reloadData];
}

#pragma mark - search

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSString *searchString = [self.searchController.searchBar text];
    
    if (searchString.length > 0) {
        @weakify(self);
        //过滤数据
        
        [NetAPIManager getSearchResultWithKeyWords:searchString block:^(NSArray *resultArray, NSError *error) {
            @strongify(self);
            self.searchResultTVC.searchResultArr = [NSMutableArray arrayWithArray:resultArray];
            self.searchResultTVC.keyWords = searchString;
            //刷新表格
            [self.searchResultTVC.tableView reloadData];
        }];
    }
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    
    searchBar.placeholder = @"";
    
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    
    searchBar.placeholder = MYLocalizedString(@"CHANGECITY_SEARCH", nil);
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -SearchResultsControllerTableViewController

- (void)selectSearchModel:(SearchResultModel *)model {
    
    //    [self dismissViewControllerAnimated:YES completion:nil];
    //    [self dismissViewControllerAnimated:YES completion:nil];
    if ([_delegate respondsToSelector:@selector(selectModel:)]) {
        [_delegate selectModel:model];
    }
}

#pragma makr - tableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        return 1;
    }else if(section == 1){
        return self.dataSource.count;
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.section == 0) {
        
        RecommndCityListCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RecommndCityListCell"];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        [cell configData:self.countyListArray];
        
        return cell;
        
    }
    //
    //    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    //    cell.textLabel.textColor = kSubitleColor;
    //    cell.textLabel.font = Font(14);
    //
    //    cell.imageView.image = [UIImage imageNamed:@"position"];
    
    SearchResultCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchResultCell"];
    
    
    SearchResultModel * model  = self.dataSource[indexPath.row];
    cell.delegate = self;
    [cell configDataWith:model Index:indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.dataSource.count < indexPath.row) {
        return;
    }
    SearchResultModel * model  = self.dataSource[indexPath.row];
    //    [self selectSearchModel:model];
    
    if ([model.type isEqualToString:@"view"]) {
        
        ScenicDescribeVC *scenicDesVC = [ScenicDescribeVC new];
        
        scenicDesVC.hidesBottomBarWhenPushed = YES;
        
        scenicDesVC.scenicid = model.ID;
        
        [self.navigationController pushViewController:scenicDesVC animated:YES];
    }else if([model.type isEqualToString:@"city"]){
        
        CityVC * cityVC = [[CityVC alloc] init];
        
        cityVC.hidesBottomBarWhenPushed = YES;
        
        cityVC.cid = model.ID;
        
        [self.navigationController pushViewController:cityVC animated:YES];
        
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    SearchHeaderView * headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SearchHeaderView"];
    headerView.delegate = self;
    if (section == 0) {
        headerView.title = MYLocalizedString(@"CHANGECITY_HOT_SEARCH", nil);
        headerView.hideDeleteBtn = YES;
        
        return headerView;
    }else if(section == 1 && self.dataSource.count > 0){
        headerView.title = MYLocalizedString(@"CHANGECITY_SEARCH_HISTROY", nil);;
        headerView.hideDeleteBtn = NO;
        
        return headerView;
    }
    
    
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    if(self.dataSource.count > 0){
        
        UITableViewHeaderFooterView * footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footerView"];
        if(!footerView){
            footerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"footerView"];
            footerView.contentView.backgroundColor = kBGColor;
            //            UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
            //            [btn setTitle:@"清空搜索记录" forState:UIControlStateNormal];
            //            [btn setTitleColor:kThemeColor forState:UIControlStateNormal];
            //            footerView.contentView.backgroundColor = [UIColor whiteColor];
            //            [btn addTarget:self action:@selector(empty) forControlEvents:UIControlEventTouchUpInside];
            //            btn.titleLabel.font = Font(14);
            //            [footerView.contentView addSubview:btn];
            //
            //            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            //                make.leading.equalTo(footerView.contentView.mas_leading);
            //                make.trailing.equalTo(footerView.contentView.mas_trailing);
            //                make.top.equalTo(footerView.contentView.mas_top);
            //                make.bottom.equalTo(footerView.contentView.mas_bottom);
            //
            //            }];
        }
        
        return footerView;
    }
    
    return nil;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    cell.layoutMargins = UIEdgeInsetsMake(0, 16, 0, 16);
    cell.separatorInset = UIEdgeInsetsMake(0, 16, 0, 16);;
    cell.preservesSuperviewLayoutMargins = NO;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 1 && self.dataSource.count == 0) {
        return 0.0001;
    }
    return  44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (self.dataSource.count > 0) {
        return  10;
    }
    return 0.0001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        return [RecommndCityListCell getHight:self.countyListArray];
        
    }else {
        
        return 50;
    }
    
    return 0;
}

#pragma mark --SearchResultCellDelegate

- (void)deleteTheIndex:(NSInteger)index {
    [self.dataSource removeObjectAtIndex:index];
    [self.tableView reloadData];
    [AppManager sharedManager].searchResultArray = self.dataSource;
}

#pragma mark ---SearchHeaderViewDelegate

- (void)deleteAllHistroy {
    [IGAlertView alertWithTitle:nil message:@"确定清空搜索记录？" cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_CONFIRM", nil) commit:^{
        [self.dataSource removeAllObjects];
        [AppManager sharedManager].searchResultArray = self.dataSource;
        [self.tableView reloadData];
    } cancel:nil];
}

#pragma mark -- RecommndCityListCellDelegate

- (void)cityListSelectCity:(City *)city {
    
    CityVC * cityVC = [[CityVC alloc] init];
    
    cityVC.hidesBottomBarWhenPushed = YES;
    
    cityVC.cid = city.cid.stringValue;
    
    [self.navigationController pushViewController:cityVC animated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    [_searchController.searchBar endEditing:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


@end

